const svgCaptcha = require('svg-captcha')
const redisConfig = require('../config/RedisConfig')
const sendMsgCode = require('../config/aliyunMessage')
const BackCode = require("../utils/BackCode");
const dayjs = require('dayjs')
const NotifyService = {
    captcha: (key, type) => {
        let captcha = svgCaptcha.create({
            size: 4,
            ignoreChars: '0o1i',
            background: '#cc9966',
            noise: 1,
            color: '#fff',
            height: 60,
            fontSize: 75
        })
        redisConfig.set(`${type}:captcha:${key}`, captcha.text, 600)
        return captcha.data
    },
    // 发送验证码接口
    sendCode: async (phone, captcha, type, key, randomCode) => {
        // 是否验证码已存在
        const ifExitsCode = await redisConfig.exists(`${type}:code:${phone}`)
        if (ifExitsCode) {
            console.log(43);
            // 截取第一部分时间
            let dateRedis = dayjs(Number((await redisConfig.get(`${type}:code:${phone}`)).split('-')[0]))
            if (dayjs(Date.now()).diff(dateRedis, 'second') <= 60) {
                return { code: '-1', data: null, msg: '验证码已存在' }
            }
        }
        //图形验证码
        if (!(await redisConfig.exists(`${type}:captcha:${key}`))) {
            return { code: -1, data: null, msg: '请先发送图形验证码' }
        }
        if (!captcha) {
            return { code: -1, data: null, msg: '缺少captcha参数' }
        }
        // 图形验证码是否正确
        const captchaRedis = await redisConfig.get(`${type}:captcha:${key}`)
        if (!(String(captcha).toLowerCase() === captchaRedis.toLowerCase())) {
            return { code: -1, data: null, msg: '图像验证码错误' }
        }
        const codeRes = (await sendMsgCode(phone, randomCode)).data;
        console.log('codeRes: ', codeRes);
        const randomCodeTime = `${Date.now()}_${randomCode}`
        redisConfig.set(`${type}:code:${phone}`, randomCodeTime, 600)//存10分钟，10分钟自动消失

        //删除图形验证码
        redisConfig.del(`${type}:captcha:${key}`)
        if (codeRes.code == '0') {
            return BackCode.buildSuccessAndMsg({ msg: '发送成功' })
        } else {
            return BackCode.buildError({ msg: '发送失败' })
        }
    }
}
module.exports = NotifyService